<template>
	<view :class="config.style">
		<FullscreenLoading :loading="loading" :config="config"></FullscreenLoading>
		<!-- #ifdef H5-->
		<Top :config="config"></Top>
		<!-- #endif -->
		<view v-if="data.status == 1">
			<view class="main-section top tabbar-bottom" :style="{paddingTop:mainPaddingTop + 'px'}">
				<template v-if="!loading && data.type=='video'">
				<view class="video-player">
					<!--视频课 播放器-->
					<VideoPlayer ref="videoPlayer" :data="data"  @sale='sale' @setVideoPlayerHeight="setVideoPlayerHeight" @returnChildData="returnChildData" />
					<!--tab切换START-->
					<view class="tabs-block">
						<view class="tabs">
							<ListTabs :value="999" :config="config" :tabs="tabs" @change="tabChange"></ListTabs>
						</view>
					</view>
					<!--tab切换END-->
				</view>
				</template>
				<template v-else>
					<view class="cover">
						<image :src="data.cover_800" mode="widthFix"></image>
						<template v-if="!loading && data.type=='audio'">
							<AudioPlayer ref="audioPlayer" :data="data" @sale='sale' @returnChildData="returnChildData" />
						</template>
					</view>
				</template>
				
				<view class="base-info" ref="baseInfo">
					<view class="title">
						{{data.title}}
					</view>
					<view class="description">
						{{data.description}}
					</view>
					<view class="column" v-if="data.column_data">
						<view class="type">专栏</view>
						<view class="column-title">{{data.column_data['title']}}</view>
					</view>
					<view class="price" v-if="Number(data.price)==0">
						免费
					</view>
					<view class="price" :class="!showSale?'hidden':''" v-else>
						￥ {{data.price}}
					</view>
					<view class="data-info">
						<view class="marking-price" :class="!showSale?'hidden':''" v-if="config.show_marking_price==1&&data.marking_price!=0">
							￥ {{data.marking_price}}
						</view>
						<view class="exp-info">
							<view class="item view">
								<uni-icons type="eye" size="10" color="#999"></uni-icons> 
								<text class="num">{{data.handling_view}}</text>
							</view>
							<view class="item sales">
								<uni-icons type="cart-filled" size="10" color="#999"></uni-icons> 
								<text class="num">{{data.handling_sales}}</text>
							</view>
							<view class="item favorites">
								<uni-icons type="star" size="10" color="#999"></uni-icons> 
								<text class="num">{{data.handling_favorites}}</text>
							</view>
						</view>
					</view>
					<view class="tabs">
						<view v-if="data.only_member == 1" class="item only-member">会员专享</view>
						<view v-if="data.score > 0" class="item score">
							<text>返还积分：</text>
							<text>{{data.score}}</text>
						</view>
					</view>
				</view>
				
				<!--支持的会员卡-->
				<view v-if="!loading && data.support_member_cards!==undefined && data.support_member_cards.length > 0  && showSale" class="member-card-info">
					<SupportMemberCards :cardsData="data.support_member_cards" @setMemberCardHeight="setMemberCardHeight"/>
				</view>
				<!--评价功能-->
				<view v-if="!loading" class="evaluate-info">
					<Evaluate type="Knowledge" :typeId="Number(data.id)" @setEvaluateHeight="setEvaluateHeight" />
				</view>
				<!--教师显示块-->
				<view v-if="data.teacher && Number(data.teacher_id) > 0" class="teacher-info">
					<Teacher :teacherId="Number(data.teacher_id)" :teacherData="data.teacher" @setTeacherInfoHeight="setTeacherInfoHeight" />
				</view>
				<!--课程详情块-->
				<view class="detail" ref="detailInfo">
					<view class="tab">
						<view class="tab-item tab-content" :class="[detailShow == 'content'?'active':'',data.play_type == 0?'only':'']" @click="toggleDetailShow('content')">
							详情
						</view>
						<view class="tab-item tab-list" :class="detailShow == 'list'?'active':''" v-if="data.play_type == 1" @click="toggleDetailShow('list')">
							目录
						</view>
					</view>
					<view class="content" :class="detailShow == 'content'?'':'hidden'">
						<!--购买后自定义描述-->
						<view class="custom-desc" v-if="data.purchase == 1 || data.can_be_used_card!=undefined && data.can_be_used_card.member_card_info.discount == 0">
							<!-- #ifdef MP-->
							<rich-text selectable="true" :nodes="util.formatRichText(data.custom_desc)"></rich-text>
							<!-- #endif -->
							<!-- #ifdef H5-->
							<view v-html="util.formatRichText(data.custom_desc)"></view>
							<!-- #endif -->
						</view>
						
						<template v-if="!loading && data.type=='image_text'">
							<ImageText ref="imageText" :data="data" />
						</template>
						
						<!--完整描述-->
						<view class="all-content" v-if="data.type!='image_text' ">
							<!-- #ifdef MP-->
							<rich-text :nodes="util.formatRichText(data.content)"></rich-text>
							<!-- #endif -->
							<!-- #ifdef H5-->
							<view v-html="util.formatRichText(data.content)"></view>
							<!-- #endif -->
						</view>
						
						<!--问答-->
						<view class="questions-info" v-if="!loading && questionsConfig.status == 1">
							<Questions type="Knowledge" :typeId="Number(data.id)" />
						</view>
						<CopyRight :data="config.copyright" />
					</view>
					
					<!--系列课目录-->
					<view class="list" :class="detailShow == 'list'?'':'hidden'">
						
						<template v-if="data.type == 'video'">
							<!--视频系列课-->
							<view class="chapter" v-for="(chapter_item,chapter_index) in data.video_chapter" :key="chapter_index">
								<view class="title">
									<view class="chapter-index">第{{chapter_index + 1}}章</view>
									<view class="chapter-title">{{chapter_item.title}}</view>
								</view>
								
								<view class="lessons" v-for="(lessons_item,lessons_index) in chapter_item.list" :key="lessons_index" :class="play_chapter_index==chapter_index&&play_lessons_index==lessons_index?'active':''">
									<view class="lessons-item" @click="playChapterIndex(chapter_index,lessons_index)">
										<view class="lessons-index">{{chapter_index+1}} - {{lessons_index+1}}</view>
										<view class="lessons-title text-ellipsis-2">
											<text class="try" v-if="lessons_item.try_play">[试看]</text>
											<text>{{lessons_item.title}}</text>
										</view>
										<view class="playing">
											<text class="iconfont">&#xe61c;</text>
										</view>
									</view>
								</view>
							</view>
						</template>
						
						<template v-if="data.type == 'audio'">
							<!--音频系列课-->
							<view class="chapter" v-for="(chapter_item,chapter_index) in data.audio_chapter" :key="chapter_index">
								<view class="title">
									<view class="chapter-index">第{{chapter_index + 1}}章</view>
									<view class="chapter-title">
										{{chapter_item.title}}
									</view>
								</view>
								
								<view class="lessons" v-for="(lessons_item,lessons_index) in chapter_item.list" :key="lessons_index" :class="play_chapter_index==chapter_index&&play_lessons_index==lessons_index?'active':''">
									<view class="lessons-item" @click="playChapterIndex(chapter_index,lessons_index)" >
										<view class="lessons-index">{{chapter_index+1}} - {{lessons_index+1}}</view>
										<view class="lessons-title text-ellipsis-2">
											<text class="try" v-if="lessons_item.try_play">[试听]</text>
											<text>{{lessons_item.title}}</text>
										</view>
										<view class="playing">
											<text class="iconfont">&#xe61c;</text>
										</view>
									</view>
								</view>
							</view>
						</template>
					</view>
				</view>
			</view>
			<template v-if="!loading && config">
				<SaleBar ref="saleBar" type="Knowledge" @getData="getData" :data="data" m="muu_classroom" :config="config" />
			</template>
		</view>
		<view class="tip" v-else>
			内容未上架，请稍后访问
		</view>
	</view>
</template>

<script>
	import { mapState,mapMutations } from 'vuex'
	// #ifdef MP
	import VideoPlayer from '../common/videoPlayer.vue'
	// #endif
	// #ifdef H5
	import VideoPlayer from '../common/videoPlayerH5.vue'
	// #endif
	import CopyRight from '@/common/components/copyright.vue' //自定义版权
	import ListTabs from "@/common/components/listTabs"; //列表tab
	import ImageText from '../common/imageText.vue'
	import AudioPlayer from '../common/audioPlayer.vue'
	import SaleBar from '../common/saleBar.vue'
	import SupportMemberCards from '../common/supportMemberCards.vue'
	import Teacher from '../common/teacher.vue'
	import Evaluate from '../common/evaluate.vue'
	import Questions from '../common/questions.vue'
	
	export default {
		components: {
			VideoPlayer,
			AudioPlayer,
			ImageText,
			SaleBar,
			SupportMemberCards,
			Teacher,
			Evaluate,
			Questions,
			CopyRight,
			ListTabs,
		},
		data() {
			return {
				loading: true, //加载中
				userInfo: {},
				urlParams: {},
				data: {},
				play_chapter_index: 0,
				play_lessons_index: 0,
				detailShow: 'content', //内容区默认显示课程详情 string content:课程详情 list:系列课目录
				showSale: this.util.setShowSale(), //IOS端是否显示销售价格
				videoPlayerHeight: 0, // 视频播放器高度
				//#ifdef MP
				mainPaddingTop: 0, 
				//#endif
				//#ifdef H5
				mainPaddingTop: 35, 
				//#endif
				tabs: [
					{'name': '简介', 'type':'base'},
					{'name': '老师', 'type':'teacher'},
					{'name': '详情', 'type':'detail'},
					{'name': '问答', 'type':'questions'},
				],
				tabIndex: 0 ,// tab下标
				baseInfoHeight: 0, // 基础信息高
				memberCardHeight: 0, // 会员卡支持高
				evaluateHeight: 0, // 评价组件高
				teacherInfoHeight: 0, // 老师组件高
				detailInfoHeight: 0, // 详情组件高
				questionsConfig: {}, // 问答配置
				questionsInfoHeight: 0 // 问答组件高（todo:问答在页面最底部，到底儿就OK）
			}
		},
		async onLoad(option) { //option为object类型，会序列化上个页面传递的参数
			await this.$onLaunched;
			this.urlParams = option
			//通过小程序码进入的获取参数
			if(option.scene){
				// options 中的 scene 需要使用 decodeURIComponent 才能获取到生成二维码时传入的 scene
				let scene = decodeURIComponent(option.scene); 
				let obj = {};
				for (var i = 0; i < scene.split('*').length;i++){
				  var arr = scene.split('*')[i].split('/');
				  obj[arr[0]] = arr[1];
				}
				this.urlParams.id = obj.id
				this.urlParams.promoter_uid = obj.u
				//console.log(this.urlParams,'scene')
			}
			
			if(this.urlParams.promoter_uid){
				uni.setStorageSync('promoter_uid',this.urlParams.promoter_uid)
			}
			
			Promise.all([this.getData(),this.getQuestionsConfig()]).then(res => {
				
				// 已购买课程进入目录页
				if(this.data.purchase == 1 && this.data.play_type == 1){
					this.detailShow = 'list'
				}
				// H5端分享设置
				//#ifdef H5
				let url = window.location.href
				
				let shareData = {
					title : this.data.title,
					desc : this.data.description,
					img: this.data.cover_200
				}
				//console.log(url)
				this.wechat.share(shareData,url)
				//#endif
			}).then(() => {
				// 计算各元素高度
				this.$nextTick(() => {
					this.getElHeight()
				})
				
				//加载完成
				this.loading = false
			})
		},
		created() {
			//获取已登录用户数据
			this.getUserInfo()
			
		},
		mounted() {
			
		},
		computed: {
			...mapState(['config'])
		},
		methods: {
			
			/**
			 * 设置视频播放器高度
			 * @param {Object} height
			 */
			setVideoPlayerHeight(height){
				if(this.data.type == 'video'){
					this.videoPlayerHeight = height
					//console.log('height',this.videoPlayerHeight)
					this.setMainPaddingTop()
				}
				//加载完成
				this.loading = false
			},
			
			setMainPaddingTop(){
				//#ifdef MP
				this.mainPaddingTop = this.mainPaddingTop + this.videoPlayerHeight + 39;
				// #endif
				//#ifdef H5
				this.mainPaddingTop = this.mainPaddingTop + this.videoPlayerHeight + 39;
				// #endif
				//console.log(this.mainPaddingTop)
			},
			
			/**
			 * 获取课程详情数据
			 */
			getData: function(){
				let that = this
				return new Promise((resolve, reject) => {
					let params = this.urlParams
					let data = {}
						data.action = 'detail'
						data.m = 'muu_classroom'
						data.id = params.id
						if(params.column_id){
							data.column_id = params.column_id
						}
						
					//获取数据
					let url = ''
						//#ifdef MP-WEIXIN
						url = 'entry/wxapp/knowledge'
						//#endif
						//#ifdef H5
						url = 'entry/site/knowledge'
						//#endif
					this.util.request({
						url : url,
						data : data,
						success: function (res) {
							if (res.data.code == 200) {
								that.data = res.data.data
								uni.setNavigationBarTitle({
								　　title:res.data.data.title
								})
								resolve(res.data)
							}
							
						}
					})
				})
			},
			
			/**
			 * 获取问答配置
			 */
			getQuestionsConfig() {
				let that = this
				return new Promise((resolve, reject) => {
					let params = this.urlParams
					let data = {}
						data.action = 'config'
						data.m = 'muu_classroom'
					//获取数据
					let url = ''
						//#ifdef MP-WEIXIN
						url = 'entry/wxapp/questions'
						//#endif
						//#ifdef H5
						url = 'entry/site/questions'
						//#endif
					this.util.request({
						url : url,
						data : data,
						success: function (res) {
							if (res.data.code == 200) {
								that.questionsConfig = res.data.data
							}else{
								// 更改tabs
								that.tabs.splice(-1,1)
								console.log('tabs',that.tabs)
							}
							resolve(res.data)
						}
					})
				})
			},
			
			/**
			 * 显示隐藏详情或目录
			 * @param {Object} value
			 */
			toggleDetailShow: function(value){
				return new Promise((resolve, reject) => {
					if(value == 'content'){
						this.detailShow = 'content'
					}else{
						this.detailShow = 'list'
					}
					
					resolve(value)
				})
			},
			/**
			 * 播放系列课索引
			 */
			playChapterIndex: function(chapter_index,lessons_index){
				if(this.data.type == 'video'){
					//触发子组件内方法
					this.$refs.videoPlayer.playChapterIndex(chapter_index,lessons_index)
				}
				if(this.data.type == 'audio'){
					//触发子组件内方法
					this.$refs.audioPlayer.playChapterIndex(chapter_index,lessons_index)
				}
			},
			/**
			 * 子组件返回的值
			 * @param {Object} res
			 */
			returnChildData: function(res){
				//console.log(res)
				this.play_chapter_index = res.chapter_index
				this.play_lessons_index = res.lessons_index
			},
			
			/**
			 * 获取已登录用户数据
			 */
			getUserInfo: function(){
				let that = this
				let userInfo = uni.getStorageSync('userInfo') || {}
				this.userInfo = userInfo
				//console.log('detail.userInfo',this.userInfo)
			},
			
			// 切换TAB(仅支持视频课)
			tabChange: function(index) {
				//console.log(index)
				// 滚动至简介
				if(index == 0){
					uni.pageScrollTo({
			　　　　　　duration:0,//过渡时间必须为0，uniapp bug，否则运行到手机会报错
			　　　　　　scrollTop: 0,//滚动到实际距离是元素距离顶部的距离减去最外层盒子的滚动距离
			　　　　	})
				}
				
				if(index == 1){
					let height = this.baseInfoHeight + this.memberCardHeight + this.evaluateHeight + 20
					//console.log('height', height)
					uni.pageScrollTo({
			　　　　　　duration:0,//过渡时间必须为0，uniapp bug，否则运行到手机会报错
			　　　　　　scrollTop: height,//滚动到实际距离是元素距离顶部的距离减去最外层盒子的滚动距离
			　　　　	})
				}
				
				if(index == 2){
					let height = this.baseInfoHeight + this.memberCardHeight + this.evaluateHeight + this.teacherInfoHeight + 30
					uni.pageScrollTo({
			　　　　　　duration:0,//过渡时间必须为0，uniapp bug，否则运行到手机会报错
			　　　　　　scrollTop: height,//滚动到实际距离是元素距离顶部的距离减去最外层盒子的滚动距离
			　　　　	})
				}
				
				if(index == 3){
					// 切换回详情显示
					this.toggleDetailShow('content').then(()=>{
						// 动态获取
						const query = uni.createSelectorQuery().in(this);
						query.select('.questions-info').boundingClientRect(data => {
							//console.log(data)
							this.questionsInfoHeight = data.bottom
							uni.pageScrollTo({
					　　　　　　duration:0,//过渡时间必须为0，uniapp bug，否则运行到手机会报错
					　　　　　　scrollTop: this.questionsInfoHeight,//滚动到实际距离是元素距离顶部的距离减去最外层盒子的滚动距离
					　　　　	})
						}).exec();
					})
				}
			},
			
			// 计算各元素高度(仅支持视频课)
			getElHeight: function() {
				const query = uni.createSelectorQuery().in(this);
				query.select('.base-info').boundingClientRect(data => {
					//console.log(data)
					this.baseInfoHeight = data.height
				}).exec();
				
				query.select('.detail').boundingClientRect(data => {
					//console.log(data)
					this.detailInfoHeight = data.height
				}).exec();
			},
			
			// 计算评价组件距离顶部高度
			setEvaluateHeight(height){
				//console.log(height)
				this.evaluateHeight = height
			},
			
			// 计算会员卡组件距离顶部高度
			setMemberCardHeight(height){
				this.memberCardHeight = height
			},
			
			// 计算老师组件距离顶部高度
			setTeacherInfoHeight(height){
				this.teacherInfoHeight = height
			},
			
			sale() {
				this.$refs.saleBar.sale()
			},
		},
		
		/**
		 * 用户点击右上角分享
		 */
		onShareAppMessage() {
			// 分享(分销)用户ID
			let userInfo = this.userInfo.memberInfo || {}
			//console.log(userInfo)
			let url = '/muu_classroom/pages/knowledge/detail?' + 'id=' + this.data.id
			if(userInfo.hasOwnProperty("uid") && userInfo.uid !== undefined){
				url = url + '&promoter_uid=' + userInfo.uid
			}
			//console.log(url)
			let share = {
				title : this.data.title,
				path : url,
				desc : this.data.description,
				success : function(res){
					
				},
			}
			
			return share
		},
		
		/**
		 * 监听用户点击右上角转发到朋友圈
		 */
		onShareTimeline() {
			
		},
		/**
		 * 监听页面滚动
		 * @param {Object} res
		 */
		onPageScroll(res) {
			// 音频播放器处理
			if(this.data.type=='audio' && res.scrollTop > 300){
				//触发子组件内方法
				this.$refs.audioPlayer.setFixed()
			}
		},
	}
</script>

<style lang="scss">
	page {
		background-color: #f8f8f8;
	}
	
	.cover {
		position: relative;
		width: 100%;
		image {
			width: 100%;
			display: block;
		}
	}
	.video-player {
		position: fixed;
		display: block;
		
		top: 0;
		left: 0;
		right: 0;
		z-index: 96;
		video {
			width: 100%;
		}
	}
	// #ifdef H5
	.video-player {
		position: fixed;
		top: 70rpx;
	}
	// #endif
	
	.tabs-block {
		border-bottom: 2rpx solid #f8f8f8;
	}
	.base-info {
		background-color: #fff;
		padding: 20rpx;
		margin-bottom: 20rpx;
		.title {
			font-size: 36rpx;
			font-weight: 600;
			color: #000;
		}
		.description {
			font-size: 28rpx;
			color: #999;
		}
		.column {
			display: flex;
			margin-top: 10rpx;
			.type {
				background-color: #ddd;
				padding: 4rpx 10rpx;
				color: #000;
				font-size: 24rpx;
				margin-right: 16rpx;
				border-radius: 10rpx;
			}
			.column-title {
				flex: 1;
				color: #000;
				font-size: 28rpx;
			}
		}
		.price {
			font-size: 36rpx;
			font-weight: 500;
			color: red;
			margin: 20rpx 0 10rpx 0;
		}
		.data-info {
			display: flex;
			.marking-price {
				font-size: 28rpx;
				color: #999;
				text-decoration: line-through;
				width: 30%;
			}
			.exp-info {
				flex: 1;
				width: 70%;
				text-align: right;
				.item {
					display: inline-block;
					color: #999;
					margin: 0 10rpx;
					font-size: 24rpx;
					.num {
						margin-left: 10rpx;
					}
				}
			}
		}
	}
	
	.detail {
		.tab {
			display: flex;
			padding: 10rpx 0;
			padding: 0 20rpx 0 20rpx;
			background-color: #fff;
			.tab-item {
				flex: 1;
				text-align: center;
				line-height: 72rpx;
				padding-bottom: 8rpx;
			}
			.tab-item.only {
				flex: none;
				text-align: left;
			}
			.tab-content {
				
			}
			.tab-list {
				
			}
			.active {
				position: relative;
				&:before {
					position: absolute;
					right: 30%;
					left: 30%;
					bottom: 0;
					height: 8rpx;
					content: '';
					-webkit-transform: scaleY(.5);
					transform: scaleY(.5);
					background-color: #03b8cf;
				}
			}
		}
		//详情
		.content {
			
			.try-content {
				margin-bottom: 16rpx;
				padding: 20rpx;
				background-color: #fff;
				user-select: text;
			}
			.custom-desc {
				padding: 20rpx;
				background-color: #fff;
				user-select: text;
			}
			.all-content {
				margin-bottom: 16rpx;
				padding: 20rpx;
				background-color: #fff;
				user-select: text;
			}
		}
		//目录
		.list {
			background-color: #fff;
			padding: 20rpx;
			.chapter {
				margin-bottom: 20rpx;
				.title {
					display: flex;
					font-size: 28rpx;
					margin-bottom: 20rpx;
					.chapter-index {
						width: auto;
						padding-right: 20rpx;
					}
					.chapter-title {
						flex: 1
					}
				}
				.lessons {
					.lessons-item {
						display: flex;
						font-size: 24rpx;
						color: #666;
						padding-left: 30rpx;
						line-height: 56rpx;
						&:active {
							background-color: #f8f8f8;
						}
						.lessons-index {
							width: 86rpx;
						}
						.lessons-title {
							flex: 1;
							.try {
								color: #f90;
								margin-right: 10rpx;
							}
						}
						.playing {
							font-size: 28rpx;
							width: 40rpx;
							padding-left: 10rpx;
							display: none;
						}
					}
				}
				.lessons.active {
					.lessons-item {
						color: #f90;
						.playing {
							display: block;
						}
					}
				}
			}
		}
	}
	
	@keyframes playing {
		
			0%{-webkit-transform: rotateY(180deg);} 
			100%{-webkit-transform: rotateY(0deg);} 
		
	}
	
</style>
